package com.diao.flink.state;

import com.google.common.collect.Lists;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

/**
 * @author: chenzhidiao
 * @date: 2021/1/19 14:42
 * @description: 测试 KeyedState 的 ListState
 *
 *
 * @version: 1.0
 */
public class KeyedListStateDemo {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
        //获取DataStream
        DataStreamSource<Tuple2<Long, Long>> tuple2DataStreamSource = env.fromElements(Tuple2.of(1L, 3L), Tuple2.of(1L, 5L), Tuple2.of(1L, 7L), Tuple2.of(2L, 4L), Tuple2.of(2L, 2L), Tuple2.of(2L, 5L));

        tuple2DataStreamSource.keyBy(0)
                .flatMap(new CountWindowAverageWithListState())
                .print();
        env.execute("TestStatefulApi");



    }
}

/**
 * ListState<T> ：这个状态为每一个 key 保存集合的值
 * get() 获取状态值
 * add() / addAll() 更新状态值，将数据放到状态中
 * clear() 清除状态
 */
class CountWindowAverageWithListState extends RichFlatMapFunction<Tuple2<Long,Long>,Tuple2<Long,Double>> {

    // 用以保存每个 key 出现的次数，以及这个 key 对应的 value 的总值
    // managed keyed state
    // 1. ListState 保存的是对应的一个 key 出现的所有元素
    private ListState<Tuple2<Long, Long>> elementsByKey;


    @Override
    public void open(Configuration parameters) throws Exception{
        //注册一个状态
        ListStateDescriptor<Tuple2<Long,Long>> descriptor = new ListStateDescriptor<Tuple2<Long,Long>>(
                "average", //状态的名称
                Types.TUPLE(Types.LONG,Types.LONG));//状态的数据类型

        elementsByKey = getRuntimeContext().getListState(descriptor);
    }


    @Override
    public void flatMap(Tuple2<Long, Long> value, Collector<Tuple2<Long, Double>> out) throws Exception {

        //获取当前key的状态
        Iterable<Tuple2<Long, Long>> currentState = elementsByKey.get();

        //如果状态还未初始化，则进行初始化
        if(currentState == null){
           elementsByKey.addAll(Collections.emptyList());
        }

        //更新状态的值
        elementsByKey.add(value);

        ArrayList<Tuple2<Long, Long>> allElements = Lists.newArrayList(elementsByKey.get());

        if (allElements.size()>=3){
            long count = 0L;
            long sum =0L;

            for (Tuple2<Long, Long> element : allElements) {
                count ++;
                sum += element.f1;
            }

            double avg = (double) sum/count;

            //输出
            out.collect(Tuple2.of(value.f0,avg));

            //清空状态值
            elementsByKey.clear();
        }

    }
}